package com.hframe.http.client;

import javax.net.ssl.X509TrustManager;
import java.security.Principal;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * https 证书管理器
 * Created by heqian on 17-6-29.
 */
public class HttpsTrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
        if ((chain == null) || (chain.length == 0))
            throw new IllegalArgumentException("null or zero-length certificate chain");
        if ((authType == null) || (authType.length() == 0))
            throw new IllegalArgumentException("null or zero-length authentication type");

        boolean br = false;
        Principal principal = null;
        for (X509Certificate x509Certificate : chain) {
            principal = x509Certificate.getSubjectX500Principal();
            if (principal != null) {
                br = true;
                return;
            }
        }
        if (!(br))
            throw new CertificateException("服务端证书验证失败！");
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

